using B.S.Data.MES.API.Applications.CangKu.Command;
using B.S.Domain.CangKu;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.CangKu.CommandHandlers
{
    /// <summary>
    /// 根据库位ID获取储位列表命令处理程序
    /// 实现三级联动中的第二级到第三级：库位 -> 储位
    /// </summary>
    public class GetChuWeiByKuWeiIdCommandHandler : IRequestHandler<GetChuWeiByKuWeiIdCommand, APIRequst<List<ChuWei>>>
    {
        private readonly IBaseRepository<ChuWei> _chuWeiRepository;
        private readonly IBaseRepository<CangKuQU> _cangKuQURepository;

        /// <summary>
        /// 构造函数，注入仓储依赖
        /// </summary>
        /// <param name="chuWeiRepository">储位仓储</param>
        /// <param name="cangKuQURepository">库位仓储</param>
        public GetChuWeiByKuWeiIdCommandHandler(
            IBaseRepository<ChuWei> chuWeiRepository,
            IBaseRepository<CangKuQU> cangKuQURepository)
        {
            _chuWeiRepository = chuWeiRepository;
            _cangKuQURepository = cangKuQURepository;
        }

        /// <summary>
        /// 处理根据库位ID获取储位列表的请求
        /// </summary>
        /// <param name="request">包含库位ID的命令对象</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>包含储位列表的API响应</returns>
        public Task<APIRequst<List<ChuWei>>> Handle(GetChuWeiByKuWeiIdCommand request, CancellationToken cancellationToken)
        {
            // 首先验证库位是否存在
            var kuWei = _cangKuQURepository.GetById(request.KuWeiId);
            // 根据库位ID查询关联的储位
            var chuWeiList = _chuWeiRepository.GetAll()
                .Where(c => c.KuWeiId == request.KuWeiId && !c.isDel)
                .OrderBy(c => c.ChuName)
                .ToList();

            return Task.FromResult(new APIRequst<List<ChuWei>>
            {
                Code = RequstCode.成功,
                Msg = "查询成功",
                Data = chuWeiList
            });
        }
    }
}